package com.xm.concurrent.base;

import com.sun.org.apache.xerces.internal.dom.PSVIAttrNSImpl;
import com.xm.concurrent.base.util.SleepUtils;
import org.omg.PortableServer.ServantLocatorPOA;

/**
 * 4.2.3中断线程
 *
 * @author xiaoming
 * @date 2021-05-23 11:35
 */
public class InterruptedThread {
    public static void main(String[] args) {

        //不停的尝试睡眠
        Thread sleepThread = new Thread(new SleepRunner(), "Sleep Thread");
        sleepThread.setDaemon(true);

        // 不停的运行
        Thread busyThread = new Thread(new BusyRunner(), "Busy Thread");
        busyThread.setDaemon(true);

        MyThread busyMyThread = new MyThread(new BusyRunner(), "Busy MyThread");
        busyMyThread.setDaemon(true);

        sleepThread.start();
        busyThread.start();
        busyMyThread.start();


        // 休眠5秒, 让两个线程充分运行
        SleepUtils.second(5);

        // 尝试中断线程
        sleepThread.interrupt();
        busyThread.interrupt();
        busyMyThread.interrupt();


        // Sleep 线程被中断了,应该返回 true, 但是抛出了 InterruptedException, 状态被还原
        // false; 线程抛出 InterruptedException , 中断标识符被清除, 返回 false
        System.out.println("Sleep Thread interrupted is " + sleepThread.isInterrupted());

        // true;  一直忙碌中, 所以线程没有被中断
        System.out.println("Busy Thread interrupted is " + busyThread.isInterrupted());
        // false ; 覆写了 Thread.interrupt()
        System.out.println("Busy MyThread interrupted is " + busyMyThread.isInterrupted());

        // 防止线程立即退出
        SleepUtils.second(2);
    }



    static class SleepRunner implements Runnable {
        @Override
        public void run() {
            while (true) {
                SleepUtils.second(10);
            }
        }
    }

    static class BusyRunner implements Runnable {
        @Override
        public void run() {
            while (true) {
            }
        }
    }


    static class MyThread extends Thread {

        public MyThread(Runnable r, String name) {
            super(r, name);

        }

        @Override
        public void interrupt() {
            super.interrupt();
            // 试图在中断后清除中断标识符,  (没得到预期效果)
            Thread.interrupted();
        }
    }

}

